from flask import Blueprint, request
from subsidy.app.service.impl.UserServiceImpl import UserServiceImpl
from subsidy.app.pojo.Result import ResultOK

from subsidy.app.flashClass.app.flashClass import FlashClass
import threading as th
import time
import threading

user_events = {}
class UserController(UserServiceImpl):
    def __init__(self):
        super().__init__()
        self.user_bp = Blueprint('user', __name__)
        self.user_login_route()
        self.user_getInfo_route()
        self.user_register_route()
        self.user_getallClassinfo_route()
        self.user_setIdentity_route()
        self.user_delIdentity_route()
        self.user_flashClass_route()
        self.user_stopflashClass_route()
        self.user_getFlashTime_route()

    def user_login_route(self):
        @self.user_bp.route('/login', methods=['POST'])
        def login_user():
            response = request.get_json()
            userInfo = {
                "username": response.get("username"),
                "password":  response.get("password"),
            }
            print(userInfo)
            data = self.login(userInfo)
            return ResultOK(data.get("status"),message=data.get("message"), data=data.get("data"))
    def user_getInfo_route(self):
        @self.user_bp.route('/info', methods=['GET'])
        def getUserInfo():
            token = request.headers.get("Authorization")
            data = self.parseJwt(token)
            return ResultOK(data.get("status"),message=data.get("message"), data=data.get("data"))

    def user_register_route(self):
        @self.user_bp.route('/register', methods=['POST'])
        def register_user():
            response = request.get_json()
            userInfo = {
                "username": response.get("username"),
                "password": response.get("password"),
            }
            print(userInfo)
            data = self.register(userInfo)
            return ResultOK(data.get("status"),message=data.get("message"), data=data.get("data"))

    def user_getallClassinfo_route(self):
        @self.user_bp.route('/AllClassInfo', methods=['GET'])
        def delete_user():
            data = {
                "idCar": request.args.get("idCar"),
                "userId":request.args.get("userId"),
            }
            data = self.getAllClassinfo(data)
            return ResultOK(data.get("status"),message=data.get("message"), data=data.get("data"))

    def user_setIdentity_route(self):
        @self.user_bp.route('/bindInfo', methods=['POST'])
        def setIdentity():
            response = request.get_json()
            userInfo = {
                "id": response.get("id"),
                "idCar": response.get("idCar"),
                "password": response.get("password"),
            }
            for k, v in userInfo.items():
                if v == "" or v == None or v == 'null':
                    return ResultOK(301,message="输入框不能为空")

            f = FlashClass(userInfo.get("idCar"),userInfo.get("password"), userInfo.get("id"))
            publicKey = f.getPublicKey()
            token = f.getLoginToken(publicKey)
            if token == 1001:
                return ResultOK(301, message="账号或密码错误")
            elif token == "ENCRYPT_PUBLIC_KEY_NO_FOUND":
                return ResultOK(301, message="未找到加密信息/加密信息已过期, 请过一会重试")
            data = self.setIdentity(userInfo)
            return ResultOK(data.get("status"),message=data.get("message"), data=token)

    def user_findIdentity_route(self):
        @self.user_bp.route('/bindInfo', methods=['GET'])
        def findIdentity():
            response = request.get_json()
            userInfo = {
                "id": response.get("id"),
                "idCar": response.get("idCar"),
            }
            ident = self.quryIdentityMapper(userInfo)
            if ident is None:
                return ResultOK(301,message="操作失败", data=None)
            return ResultOK(200,message="操作成功", data=ident)

    def user_delIdentity_route(self):
        @self.user_bp.route('/delIdentity', methods=['POST'])
        def delIdentity():
            response = request.get_json()
            userInfo = {
                "id": response.get("id"),
            }
            data = self.delIdentityService(userInfo)
            return ResultOK(data.get("status"),message=data.get("message"), data=data.get("data"))



    def user_flashClass_route(self):

        def user_function(user_id, userInfo):
            count = 0
            event = user_events[user_id]
            while not event.is_set():
                print(f"用户 {user_id} 的函数正在运行，计数: {count}")
                count += 1
                if count == 1:
                    self.flashClassService(userInfo)
                time.sleep(1)
            print(f"用户 {user_id} 的函数已停止")

        @self.user_bp.route('/flashClass', methods=['POST'])
        def flashClass():
            response = request.get_json()
            userInfo = {
                "id": response.get("id"),
                "idCar": response.get("idCar"),
                "password": response.get("password"),
            }
            print(userInfo)
            user_id = userInfo.get('id')
            useStatus = self.readDb.get(user_id).decode("utf-8")
            print("useStatus: ", useStatus)
            if useStatus is None or useStatus=='1':
                if user_id not in user_events:
                    user_events[user_id] = threading.Event()

                user_events[user_id].clear()
                thread = threading.Thread(target=user_function, args=(user_id,userInfo))
                thread.start()
                self.readDb.set(user_id, "0")
                return f"开始刷课, 一分钟更新一次进度，请稍等..."
            else:
                return f"当前正在刷课, 请先停止"
            # return ResultOK(200,message="正在刷课", data=None)
    def user_stopflashClass_route(self):
        @self.user_bp.route('/stopflashClass', methods=['POST'])
        def stopflashClass():
            response = request.get_json()
            userInfo = {
                "id": response.get("id"),
                "idCar": response.get("idCar"),
                "password": response.get("password"),
            }
            user_id = userInfo.get('id')
            self.readDb.set(user_id, "1")
            if user_id in user_events:
                user_events[user_id].set()
                return f"当前用户刷课已停止"
            else:
                return f"当前没有进行刷课"

    def user_getFlashTime_route(self):
        @self.user_bp.route('/getFlashTime', methods=['POST'])
        def getFlashTime():
            response = request.get_json()
            userInfo = {
                "id": response.get("id"),
                "idCar": response.get("idCar"),
                "password": response.get("password"),
            }
            print(userInfo)
            data = self.readDb.get(userInfo.get("id")+":info")
            if data is not None:
                return data.decode("utf-8")
            else:
                return "暂无信息"